package cn.java78.springboot.myschool.ctrl;

import cn.java78.springboot.myschool.entity.Student;
import cn.java78.springboot.myschool.pojo.AjaxPage;
import cn.java78.springboot.myschool.pojo.AjaxResult;
import cn.java78.springboot.myschool.pojo.Page;
import cn.java78.springboot.myschool.service.GradeService;
import cn.java78.springboot.myschool.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author oldliu
 * @since 1.0
 */
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("student")
@Api("管理学生功能")
@Slf4j
public class StudentController {
    @Value("${upload.path}")
    private String picpath;

    //private StudentService adminService= SpringUtil.getBean(StudentService.class);
    @Resource
    private StudentService studentService;//= SpringUtil.getBean(StudentService.class);
    @Resource
    private GradeService gradeService;

    @PostMapping("add")
    public AjaxResult add(Student stu,@RequestPart(name = "file") MultipartFile m){
        if(log.isDebugEnabled())
        log.debug(stu+"是要保存的对象");
        if(!m.isEmpty()){

            File f=new File(picpath+"/images");
            if(!f.exists())
                f.mkdirs();

            String oldName=m.getOriginalFilename();
            String houzhui=oldName.substring( oldName.lastIndexOf('.'));
            String newName= UUID.randomUUID()+houzhui;
            try {
                m.transferTo(new File(f,newName));
                stu.setIdcardpic("images/"+newName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        int r=this.studentService.add(stu);
        log.info("增加新生的结果："+r);
        return AjaxResult.success();
    }

    @GetMapping("ajaxsearch2")
    public AjaxPage<Student> ajaxsearch2(@RequestParam(name = "sname", required = false) String sname,
                                         @RequestParam(name = "qq", required = false) String qq, @RequestParam(name = "wechat", required = false) String wechat,
                                         @RequestParam(name = "dateStart", required = false) Date start,
                                         @RequestParam(name = "dateEnd", required = false) Date end,
                                         @RequestParam(name = "page", defaultValue = "1") int page) {
        Page<Student> p = studentService.search(wechat, qq, sname, start, end, page);

        return  new AjaxPage<>(p.getPageNo(),p.getTotalElements(),p.getDatas());
    }
    @ApiOperation("学生搜索")
    @GetMapping("ajaxsearch")
    public Page<Student> ajaxsearch(@ApiParam("学生姓名") @RequestParam(name = "sname", required = false) String sname,
                                    @ApiParam("学生QQ")@RequestParam(name = "qq", required = false) String qq, @RequestParam(name = "wechat", required = false) String wechat,
                                    @ApiParam("入学时间的查询起点，非必须")   @RequestParam(name = "dateStart", required = false) Date start,
                                    @ApiParam("入学时间的查询终点，非必须")     @RequestParam(name = "dateEnd", required = false) Date end,
                                    @ApiParam("页号，默认是1")     @RequestParam(name = "page", defaultValue = "1") int page,HttpServletRequest req) {
        System.out.println(req.getHeader("token")+"?????????????????????????");
        Page<Student> p = studentService.search(wechat, qq, sname, start, end, page);

        return p;
    }

    @PostMapping(value = "add1", produces ="application/json;charset=utf-8")
    public AjaxResult add1(Student student, @RequestPart(name="file",required = false) MultipartFile m, HttpServletRequest req) {
    //public AjaxResult add1(@RequestBody Student student, @RequestPart(name="file",required = false) MultipartFile m, HttpServletRequest req) {
        System.out.println(m+">>>>>>>>>>>>>>>>>>"+student);
        System.out.println(m.isEmpty());
        if(m!=null&&!m.isEmpty()){

            //m.getName()
            //ServletContext application = req.getServletContext();
            String images =this.picpath+"/images";// application.getRealPath("/images");
            File f=new File(images);
            if(!f.exists())
                f.mkdirs();

            String oldName=m.getOriginalFilename();
            String houzhui=oldName.substring( oldName.lastIndexOf('.'));
            String newName= UUID.randomUUID()+houzhui;
            try {
                m.transferTo(new File(f,newName));
                student.setIdcardpic("images/"+newName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        int add = this.studentService.add(student);
        if (add > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }
    @PostMapping(value = "ajaxadd", produces ="application/json;charset=utf-8")
    public AjaxResult add2(Student student, @RequestPart(name="file",required = false) MultipartFile m, HttpServletRequest req) {
        System.out.println(m+">>>>>>>>>>>>>>>>>>");
        if(!m.isEmpty()){
            //m.getName()
            ServletContext application = req.getServletContext();
            String images = application.getRealPath("/images");
            File f=new File(images);
            if(!f.exists())
                f.mkdirs();

            String oldName=m.getOriginalFilename();
            String houzhui=oldName.substring( oldName.lastIndexOf('.'));
            String newName= UUID.randomUUID()+houzhui;
            try {
                m.transferTo(new File(f,newName));
                student.setIdcardpic("images/"+newName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        int add = this.studentService.add(student);
        if (add > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }
    //@DeleteMapping
    @GetMapping("del/{stuno}")
    public AjaxResult del(@PathVariable long stuno){

        return AjaxResult.success();
    }
    @GetMapping("get/{stuno}")
    public AjaxResult get(@PathVariable long stuno){
        return AjaxResult.success();
    }
    @PostMapping("update")
    public AjaxResult update(Student stu){
        return AjaxResult.success();
    }
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        // true:允许输入空值，false:不能为空值

        //第二个参数是特定的属性名称
        //binder.registerCustomEditor(Date.class,"examdate",new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm"), true));
    }

}
